/*
 * Copyright 2008-2010 GP Software
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 * FixedWidthPropertyWrapper.java | Created on Jul 16, 2010
 */
package org.gp.fileGenerator;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Properties;

/**
 * Wrapper class for fixed width properties
 *
 * @author Paul Augustine C. Mendoza
 */
public abstract class FixedWidthPropertyWrapper implements Serializable {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    private static final String SPACE = " ";
    private Properties props;
    private File definitionFile;

    protected FixedWidthPropertyWrapper(File definitionFile) {
        this.definitionFile = definitionFile;
        initialize();
    }            

    private void initialize() {
        this.props = new Properties();
        InputStream is = null;
        try {
            is = new FileInputStream(this.definitionFile);
            this.props.load(is);
        } catch (IOException e) {
            logger.error("Error in initializing.", e);
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    logger.error("Error in closing stream.", e);
                }
            }
        }
    }

    protected String buildString(String value, int length) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            sb.append((i < value.length()) ? value.charAt(i) : SPACE);
        }
        return sb.toString();
    }

    protected int getPropertyWidth(String propertyName) {
        return Integer.parseInt(this.props.getProperty(propertyName));
    }
    
}
